package com.hk.aspect;

import com.alibaba.fastjson.JSONObject;
import com.hk.exception.BizException;
import com.hk.utils.ValidationResult;
import com.hk.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class CommonParamValidateAop implements Ordered {

    @Pointcut(value = "@annotation(com.hk.annotation.CommonParamValidate)")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Object[] args = joinPoint.getArgs();
        for (int argIndex = 0; argIndex < args.length; argIndex++) {
            for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
                if (!(paramAnnotation instanceof RequestBody)) {
                    continue;
                }
            }
            ValidationResult validationResult = ValidatorUtils.validateEntityResult(args[argIndex]);
            if (validationResult.isHasErrors()) {
                Map<String, String> errorMsg = validationResult.getErrorMsg();
                throw new BizException("参数不正确：" + JSONObject.toJSONString(errorMsg));
            }
        }
    }


    /**
     * 指定切面执行的顺序，从小到大
     * @return
     */
    @Override
    public int getOrder() {
        return 2;
    }
}
